package com.realife.ysuper.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.realife.ysuper.dao.CategoryDao;
import com.realife.ysuper.entity.CategoryEntity;
import com.realife.ysuper.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 可以直接使用 baseMapper,不用注入 mapper 接口
 *
 * @Autowired protected M baseMapper;
 * @Override public M getBaseMapper() {
 * return baseMapper;
 * }
 */
@Slf4j
@Service("categoryService")
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

//    @Autowired
//    private CategoryDao categoryDao;

    @Override
    public List<CategoryEntity> listWithTree() {

        //查询出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //level-1
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentId() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        //发送一条SQL语句 --> 查出所有菜单 --> 利用递归方法组合成父子关系


        return entities;
    }


    /**
     * 递归查找所有菜单的子菜单
     */
    public List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentId() == root.getId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}